<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button type="primary" @click="addschooladdress()">添加校区</a-button>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <el-table
          :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
          style="width: 100%"
        >
          <el-table-column label="序号" width="60">
            <template slot-scope="scope">{{scope.$index+1}}</template>>
          </el-table-column>
          <el-table-column prop="name" label="校区名称" width="180">
            <template slot-scope="scope">
              <el-button
                type="text"
                v-text="scope.row.name"
                @click="watchthis = true ; index = scope.row.ID"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column sortable prop="type" label="类型" width="80"></el-table-column>
          <el-table-column sortable prop="address" label="校区地区">
            <template slot-scope="scope">
              <span v-if="scope.row.address">
                {{scope.row.address.province }}
                {{scope.row.address.city }}
                {{scope.row.address.area }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="detailedaddress" label="校区地址"></el-table-column>
          <el-table-column sortable prop="phonenum" label="电话"></el-table-column>
          <el-table-column align="right" width="200px">
            <template slot="header" slot-scope="scope">
              <input
                class="form-control form-control-sm"
                :key="scope.$index"
                v-model.lazy="search"
                placeholder="输入关键字搜索"
              />
            </template>
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="addschooladdress(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="delschooladdress(scope.row.ID)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          @current-change="currentChange"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="tableData.length"
        ></el-pagination>

        <el-dialog class="school-form" :title="title" width="510px" :visible.sync="setaddress">
          <el-form
            :model="schooladdressbyid"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            size="mini"
          >
            <el-form-item label="校区名称" prop="name">
              <el-input v-model="schooladdressbyid.name"></el-input>
            </el-form-item>
            <el-form-item label="所属区域" prop="address">
              <el-cascader
                filterable
                :options="address()"
                :props="{value:'label'}"
                v-model="selectedOptions"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="校区地址" prop="detailedaddress">
              <el-input v-model="schooladdressbyid.detailedaddress"></el-input>
            </el-form-item>

            <el-form-item label="校区类型" prop="type">
              <el-select v-model="schooladdressbyid.type" allow-create placeholder="请选择校区类型">
                <el-option
                  v-for="(item, i) in options"
                  :key="`1organization_school${i}`"
                  :label="item.value"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系人">
              <el-input v-model="schooladdressbyid.username"></el-input>
            </el-form-item>
            <el-form-item label="校区电话">
              <el-input v-model="schooladdressbyid.phonenum"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
            <el-button @click="setaddress = false" size="mini">取 消</el-button>
          </div>
        </el-dialog>
        <el-dialog class="school-form" title="班级详情" width="510px" :visible.sync="watchthis">
          <el-form class="htedialogtext" v-if="watchthis" label-width="150px" size="mini">
            <el-form-item label="校区名称:">
              <span v-text="scope.name"></span>
            </el-form-item>
            <el-form-item label="校区地址:">
              <span v-text="scope.detailedaddress"></span>
            </el-form-item>
            <el-form-item label="所属地区:">
              <span v-if="scope.address">
                {{scope.address.province }}
                {{scope.address.city }}
                {{scope.address.area }}
              </span>
            </el-form-item>
            <el-form-item label="校区类型:">
              <span>{{ scope.type }}</span>
            </el-form-item>
            <el-form-item label="联系人:">
              <span>{{ scope.username }}</span>
            </el-form-item>
            <el-form-item label=" 联系电话:">
              <span>{{scope.phonenum }}</span>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="watchthis = false" type="primary" plain size="mini">返回</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  asynccreateschooladdress,
  asyncdelschooladdress
} from "../../../../plugins/api";
export default {
  name: "organization_school",
  data() {
    return {
      search: "",
      currentPage: 1,
      pagesize: 10,
      title: "添加校区",
      selectedOptions: [],
      options: [
        {
          value: "自营"
        },
        {
          value: "合作"
        },
        {
          value: "加盟"
        },
        {
          value: "代理"
        }
      ],
      schooladdressbyid: {
        ID: "",
        name: "",
        type: "",
        address: {},
        detailedaddress: "",
        phonenum: "",
        username: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入校区名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        type: [
          { required: true, message: "请选择校区类型", trigger: "change" }
        ],
        address: [
          { required: true, message: "请选择校区地区", trigger: "change" }
        ],
        detailedaddress: [
          { required: true, message: "请输入校区地址", trigger: "blur" }
        ]
      },
      setaddress: false,
      watchthis: false,
      index: 0
    };
  },
  mounted() {
    this.selectedOptions = Object.values(this.getschool.addr).reverse();
  },
  computed: {
    ...mapGetters(["getschooladdress", "getschooluser", "getschool"]),
    tableData() {
      const { getschooladdress, search } = this;
      return getschooladdress.filter(data => {
        return Object.values(data)
          .join("")
          .toLowerCase()
          .includes(search.toLowerCase());
      });
    },
    scope() {
      return this.getschooladdress.find(v => v.ID === this.index) || {};
    }
  },
  watch: {
    selects(v) {
      const { tableData, currentPage, pagesize } = this;
      if (v) {
        this.selectUser = tableData
          .slice((currentPage - 1) * pagesize, currentPage * pagesize)
          .map(v => v.openid);
      } else {
        this.selectUser = [];
      }
    },
    search() {
      this.selects = false;
      this.selectUser = [];
      this.currentPage = 1;
    }
  },
  methods: {
    currentChange(index) {
      this.currentPage = index;
    },
    addschooladdress(v) {
      this.setaddress = true;
      if (v) {
        this.title = "修改校区";
        const data = JSON.parse(JSON.stringify(v));
        if (v.address) {
          this.selectedOptions = Object.values(v.address).reverse();
        } else {
          this.selectedOptions = Object.values(this.getschool.addr).reverse();
        }
        this.schooladdressbyid = data;
      } else {
        this.title = "添加校区";
        this.schooladdressbyid = {
          name: "",
          type: "自营",
          address: {},
          detailedaddress: "",
          phonenum: "",
          username: ""
        };
      }
    },
    delschooladdress(ID) {
      this.$confirm("此操作将永久删除该校区, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await asyncdelschooladdress({ ID });
            await this.$store.dispatch("actionschooladdress");

            this.$message.success("删除成功");
          } catch (err) {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    address() {
      const address = window.address || [];
      return address;
    },
    handleChange() {
      const data = {
        province: this.selectedOptions[0],
        city: this.selectedOptions[1],
        area: this.selectedOptions[2]
      };
      this.schooladdressbyid.address = data;
    },
    async submitForm() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          const data = this.schooladdressbyid.ID ? "修改" : " 添加";
          this.schooladdressbyid.address = {
            province: this.selectedOptions[0],
            city: this.selectedOptions[1],
            area: this.selectedOptions[2]
          };
          try {
            await asynccreateschooladdress(this.schooladdressbyid);
            await this.$store.dispatch("actionschooladdress");
            this.setaddress = false;
            this.$message.success(`${data}成功`);
          } catch (err) {
            this.$message.error(`${data}失败`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");

          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.dialog-footer {
  text-align: center;
}
</style>